﻿using System;
using System.Runtime.InteropServices;
using Microsoft.Win32;
using System.IO;
using System.Net;
using System.Net.NetworkInformation;
using System.Threading;

namespace BingPic {
    class Program {
        static void Main(string[] args) {
            //if (!IsConn()) Console.WriteLine("貌似没有连上网");
            string path = Environment.CurrentDirectory;
            //SetPic(path);
            while (!IsConn()) Thread.Sleep(3000);
            if (args.Length < 1 || (args[0] == "0" && args.Length == 1)) SetPic(path);
            else if (args[0] == "1" && args.Length == 1) DownloadPic(args);
            else if ((args[0] == "0" && args[1] == "1") || (args[1] == "0" && args[0] == "1")) {
                SetPic(path);
                DownloadPic(args);
            }
        }

        public class WinApi {
            [DllImport("user32.dll", EntryPoint = "SystemParametersInfo")]
            public static extern int SystemParametersInfo(int uAction, int uParam, string lpvParam, int fuWinIni);
        }
        private static void Set(string picPath) {
            /*
            Bitmap bitmap = new Bitmap(picPath + @"\b.jpg");
            BitmapData data = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height),
                ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
            Bitmap bitmap2 = new Bitmap(bitmap.Width, bitmap.Height, data.Stride, PixelFormat.Format24bppRgb,
                data.Scan0);//将图片转换成BMP格式
            bitmap2.Save(picPath + @"\newb.bmp", ImageFormat.Bmp);
            bitmap.UnlockBits(data);
            string bmpPath = picPath + @"\newb.bmp"; //壁纸的位置
            我特么就不明白为啥教程都说必须bmp，明明jpg也行，shit
             */
            string bmpPath = picPath + @"\b.jpg";
            WinApi.SystemParametersInfo(20, 1, bmpPath, 0x1 | 0x2); //更换壁纸
            RegistryKey hk = Registry.CurrentUser;
            RegistryKey run = hk.CreateSubKey(@"Control Panel\Desktop\");
            run.SetValue("Wallpaper", bmpPath); //将新图片路径写入注册表
        }
        private static bool IsConn() {
            PingReply res;
            Ping ping = new Ping();
            try
            {
                res = ping.Send("cn.bing.com");
                if (res.Status != IPStatus.Success)
                    return false;
                else
                    return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
        private static void SetPic(string path) {
            //var time = DateTime.Now.ToString();
            //Console.WriteLine("创建缓存目录……");
            //string sPath = @"D:\aaa";
            //if (!Directory.Exists(sPath))
            //{
            //    Directory.CreateDirectory(sPath);
            //}
            Console.WriteLine("获取图片中……");
            string url = string.Empty;
            GetUrl(ref url);
            WebClient mywebclient = new WebClient();
            mywebclient.DownloadFile("http://cn.bing.com" + url, path + @"\b.jpg");
            Console.WriteLine("获取成功，正在设置为壁纸……");
            Set(path);
        }
        private static void Connect(ref string res, short i) {
            HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create("http://www.bing.com/hpimagearchive.aspx?format=xml&idx=" + i + "&n=1&mbl=1&mkt=zh-cn");
            webrequest.KeepAlive = false;
            webrequest.Method = "GET";
            using (HttpWebResponse webresponse = (HttpWebResponse)webrequest.GetResponse())
            using (StreamReader loResponseStream = new StreamReader(webresponse.GetResponseStream()))
                res = loResponseStream.ReadToEnd();
        }
        private static void ProcessXml(ref string xmlString) {
            using (System.Xml.XmlReader reader = System.Xml.XmlReader.Create(new StringReader(xmlString)))
            {
                reader.ReadToFollowing("urlBase");
                xmlString = reader.ReadElementContentAsString();
            }
        }
        private static void DownloadPic(string[] args) {
            string imgDir = string.Empty;
            //if (args.Length == 1) imgDir = @"D:\aaa\bingpic";
            imgDir = @"D:\aaa\bingpic\";
            if (!Directory.Exists(imgDir))
                Directory.CreateDirectory(imgDir);
            for (short i = 6; i >= 0; i--)
            {
                var imageFileName = imgDir + DateTime.Today.AddDays(-i).ToString("yyy-MM-dd") + ".jpg";

                if (!File.Exists(imageFileName))
                {
                    string response = null;
                    Connect(ref response, i);
                    ProcessXml(ref response);
                    Console.WriteLine(response);
                    //AnotherWayToGetUrlbase(ref response, i);
                    try
                    {
                        using (WebClient client = new WebClient())
                            client.DownloadFile("http://www.bing.com" + response + "_1920x1200.jpg", imageFileName);
                    }
                    catch (WebException shit)
                    {
                        Console.WriteLine(shit.Message);
                    }
                }
            }
        }
        private static void GetUrl(ref string url) {
            WebClient mywebclient = new WebClient();
            string jsonpath = "http://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1&mkt=zh-CN";
            mywebclient.DownloadFile(jsonpath, @"D:\aaa\s.txt");
            string json = new StreamReader(@"D:\aaa\s.txt").ReadToEnd();
            var obj = Newtonsoft.Json.Linq.JObject.Parse(json);
            url = Convert.ToString(obj["images"][0]["url"]);
        }
        private static void AnotherWayToGetUrlbase(ref string url, int i)//还有点问题，先别用了，懒得看了……
        {
            WebClient mywebclient = new WebClient();
            string jsonpath = "http://www.bing.com/HPImageArchive.aspx?format=js&idx="+"i"+"&n=1&mkt=zh-CN";
            string today = @"D:\aaa\" + DateTime.Today.AddDays(-i).ToString("yyy - MM - dd") + ".txt";
            mywebclient.DownloadFile(jsonpath, today);
            string json = new StreamReader(@today).ReadToEnd();
            var obj = Newtonsoft.Json.Linq.JObject.Parse(json);
            url = Convert.ToString(obj["images"][0]["urlbase"]);
        }
    }
}
